package com.youkeda.test.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("error.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 具体处理客户端的数据信息
        System.out.println("receive message. ");
        ByteBuf buf = (ByteBuf) msg;
        String rev = getMessage(buf);
        System.out.println(rev);
    }

    private String getMessage(ByteBuf buf) {
        byte[] con = new byte[buf.readableBytes()];
        buf.readBytes(con);
        try {
            return new String(con, Charset.forName("GBK"));
        } catch (Exception e) {
            System.out.println("trans bytes to string error. ");
            e.printStackTrace();
            return null;
        }
    }
}
